package com.emily.test.controller;

import com.alibaba.fastjson.JSONObject;
import com.emily.test.constant.ReturnValueConstants;
import com.emily.test.controller.result.ResponseResult;
import com.emily.test.model.OContact;
import com.emily.test.model.ONews;
import com.emily.test.service.EmailService;
import com.emily.test.service.OContactService;
import com.emily.test.service.RedisService;
import com.emily.test.utils.ConstentUtil;
import com.emily.test.utils.DateUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 联系我们接口
 *
 * @author tqx
 */
@RestController
@RequestMapping(value = "oContactController")
@Api(value = "oContactApi", description = "oContact接口类", position = 1, produces = MediaType.APPLICATION_JSON_VALUE)
public class OContactController {

    private Logger logger = LoggerFactory.getLogger(OContactController.class);
    @Autowired
    private OContactService oContactService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private EmailService emailService;

    /**
     * 根据条件查询<联系我们>列表
     *
     * @param jsonObject
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "根据条件查询<联系我们>列表", notes = "根据条件查询<联系我们>列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID"),
            @ApiImplicitParam(name = "eMail", value = "邮箱"),
            @ApiImplicitParam(name = "phone", value = "电话"),
            @ApiImplicitParam(name = "companyCode", value = "公司code"),
            @ApiImplicitParam(name = "logo", value = "公司logo"),
            @ApiImplicitParam(name = "address", value = "地址")
    })
    @PostMapping(value = "selectContactListByCondition")
    public ResponseResult selectContactListByCondition(@RequestBody(required = false) JSONObject jsonObject, HttpServletRequest request) throws Exception {
        OContact oContact = (OContact) ConstentUtil.json2Object(jsonObject, OContact.class);
        String token = request.getHeader("token");
        Map<String,Object> userMap= (Map<String, Object>) redisService.get(token);
        String companyCode=null;
        if(!ConstentUtil.isEmpty(jsonObject)){
            if(!ConstentUtil.isEmpty(jsonObject.getString("companyCode"))){
                companyCode=jsonObject.getString("companyCode");
            }
        }
        if(!ConstentUtil.isEmpty(userMap)){
            if(!ConstentUtil.isEmpty(userMap.get("companyCode"))){
                companyCode= userMap.get("companyCode") == null ? null : (String) userMap.get("companyCode");
            }
        }
//        companyCode= userMap.get("companyCode") == null ? null : (String)userMap.get("companyCode");
        oContact.setCompanyCode(companyCode);
        try {
            List<OContact> oContactList = oContactService.selectContactListByCondition(oContact);
            if (!ConstentUtil.isEmpty(oContactList) && oContactList.size() == 1) {
                return ResponseResult.success(oContactList.get(0));
            }
            logger.info("根据查询条件获取’联系我们‘信息成功:{}", oContactList);
            return ResponseResult.success(oContactList);
        } catch (Exception e) {
            logger.info("根据查询条件获取’联系我们‘信息异常:{}", e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.QUERY_FAILURE);
        }
    }

    /**
     * 插入一条联系我们
     *
     * @param jsonObject
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "插入一条联系我们", notes = "插入一条联系我们")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID"),
            @ApiImplicitParam(name = "eMail", value = "电子邮件"),
            @ApiImplicitParam(name = "companyCode", value = "公司code"),
            @ApiImplicitParam(name = "logo", value = "公司logo"),
            @ApiImplicitParam(name = "phone", value = "电话"),
            @ApiImplicitParam(name = "address", value = "地址")
    })
    @PostMapping(value = "insertContact")
    public ResponseResult insertContact(@RequestBody JSONObject jsonObject, HttpServletRequest request) throws Exception {
        OContact oContact = (OContact) ConstentUtil.json2Object(jsonObject, OContact.class);
        String token = request.getHeader("token");
        Map<String, Object> userMap = (Map<String, Object>) redisService.get(token);
        String companyCode = userMap.get("companyCode") == null ? null : (String) userMap.get("companyCode");
        oContact.setCompanyCode(companyCode);

        OContact oc = new OContact();
        oc.setCompanyCode(companyCode);

        try {
            List<OContact> ocList = oContactService.selectContactListByCondition(oc);
            if (!ConstentUtil.isEmpty(ocList)) {
                oc.setId(ocList.get(0).getId());
                oc.setAddress(oContact.getAddress());
                oc.seteMail(oContact.geteMail());
                oc.setLogo(oContact.getLogo());
                oc.setPhone(oContact.getPhone());
                int nu = oContactService.updateContact(oc);
                logger.info(ReturnValueConstants.UPDATE_SUCCESS);
                return ResponseResult.success(nu);
            }
            int num = oContactService.insertContact(oContact);
            logger.info("插入一条联系我们成功,插入条数:{}", num);
            return ResponseResult.success(num);
        } catch (Exception e) {
            logger.info("插入一条联系我们异常", e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.ADD_FAILURE);
        }
    }

    /**
     * 修改联系我们
     *
     * @param jsonObject
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "修改联系我们", notes = "修改联系我们")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "ID", required = true),
            @ApiImplicitParam(name = "eMail", value = "电子邮件"),
            @ApiImplicitParam(name = "phone", value = "电话"),
            @ApiImplicitParam(name = "company_code", value = "公司code"),
            @ApiImplicitParam(name = "logo", value = "公司logo"),
            @ApiImplicitParam(name = "address", value = "地址")
    })
    @PostMapping(value = "updateContact")
    public ResponseResult updateContact(@RequestBody JSONObject jsonObject) throws Exception {
        OContact oContact = (OContact) ConstentUtil.json2Object(jsonObject, OContact.class);
        if (ConstentUtil.isEmpty(oContact)) {
            return ResponseResult.fail("插入信息" + ReturnValueConstants.IS_NOT_ALLOW_NULL);
        }
        if (ConstentUtil.isEmpty(oContact.getId())) {
            return ResponseResult.fail("ID" + ReturnValueConstants.IS_NOT_ALLOW_NULL);
        }
        try {
            int num = oContactService.updateContact(oContact);
            logger.info("修改一条信息成功,修改条数:{}", num);
            return ResponseResult.success(num);
        } catch (Exception e) {
            logger.info("修改一条信息异常", e);
            e.printStackTrace();
            return ResponseResult.fail(ReturnValueConstants.UPDATE_FAILURE);
        }
    }

    /**
     * 删除多条记录
     *
     * @param jsonObject 其中ids的格式为:ids={1,2,3,4}
     * @return
     */
    @ApiOperation(value = "删除多条记录", notes = "删除多条记录")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ids", value = "ids", required = true)
    })
    @PostMapping(value = "deleteContactByIds")
    public ResponseResult deleteContactByIds(@RequestBody JSONObject jsonObject) {
        String ids = jsonObject.getString("ids").replaceAll("\\[", "").replaceAll("]", "");
        String[] idStr = ids.split(",");
        List<OContact> oContactList = new ArrayList<OContact>();
        if (idStr.length != 0) {
            for (int i = 0; i < idStr.length; i++) {
                OContact oContact = new OContact();
                oContact.setId(ConstentUtil.strToInteger(idStr[i]));
                oContactList.add(oContact);
            }
        }
        try {
            int num = oContactService.deleteContactByIds(oContactList);
            logger.info("ids为{}的信息已删除", ids);
            return ResponseResult.success(oContactList);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail("删除失败");
        }
    }
    @Value(value="${spring.mail.username}")
    private String sender;
    @ApiOperation(value = "发送邮件", notes = "游客填写的信息发送到公司邮箱")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "名字", required = true),
            @ApiImplicitParam(name = "email", value = "邮箱", required = true),
            @ApiImplicitParam(name = "phone", value = "电话", required = true),
            @ApiImplicitParam(name = "info", value = "消息", required = true),
            @ApiImplicitParam(name = "companyCode", value = "公司code", required = true),
            @ApiImplicitParam(name = "cEmail", value = "公司邮箱", required = true),

    })
    @PostMapping(value = "toEmail")
    public ResponseResult toEmail(@RequestBody JSONObject jsonObject) {
        logger.info("联系我们数据{}", jsonObject.toJSONString());
        String sen=sender;
        String receiver=jsonObject.getString("cEmail");
        String title="您有一封联系邮件需要查收";
        String text=jsonObject.getString("name")+"在您的官网留下信息："+jsonObject.get("info")+"。并留下了自己联系方式,邮箱："+jsonObject.getString("email")+",电话："+jsonObject.getString("phone");
        try {
            emailService.send(sen,receiver,title,text);
            logger.info("发送的信息为{}", text);
            return ResponseResult.success("发送成功",text);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.fail("发送失败");
        }
    }


}
